package com.cardone.platform.authority.controller;

import java.util.List;
import java.util.Map;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cardone.common.dto.PaginationDto;
import com.cardone.context.Constants;
import com.cardone.platform.authority.dto.PeVaRuTransactModeDto;
import com.cardone.platform.authority.dto.PermissionDto;
import com.cardone.platform.authority.service.AuthorityService;
import com.cardone.platform.authority.validator.PeVaRuTransactModeValidator;
import com.cardone.platform.authority.validator.PermissionValidator;
import com.cardone.platform.authority.vo.PermissionVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 许可
 * 
 * @author yaoht
 */
@Setter
@Slf4j
@RequestMapping(PermissionController.Paths.ROOT)
@Controller
public class PermissionController {
	/**
	 * models集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum models {
		/**
		 * 消息
		 */
		message,

		/**
		 * 许可
		 */
		permission,

		/**
		 * 许可、验证规则与处理模式
		 */
		peVaRuTransactMode;
	}

	/**
	 * 路径集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum Paths {
		/**
		 * 许可主界面
		 */
		index,

		/**
		 * 许可、验证规则与处理模式编辑视图路径
		 */
		PE_VA_RU_TRANSACT_MODEEdit("peVaRuTransactMode/edit"),

		/**
		 * 许可、验证规则与处理模式主界面视图路径
		 */
		PE_VA_RU_TRANSACT_MODEIndex("peVaRuTransactMode/index"),

		/**
		 * 许可、验证规则与处理模式编辑视图路径
		 */
		PE_VA_RU_TRANSACT_MODENew("peVaRuTransactMode/new"),

		/**
		 * 许可、验证规则与处理模式查看编辑视图路径
		 */
		PE_VA_RU_TRANSACT_MODEView("peVaRuTransactMode/view"),

		/**
		 * 许可编辑视图路径
		 */
		PERMISSIONEdit("permission/edit"),

		/**
		 * 许可主界面视图路径
		 */
		PERMISSIONIndex("permission/index"),

		/**
		 * 许可编辑视图路径
		 */
		PERMISSIONNew("permission/new"),

		/**
		 * 许可查看编辑视图路径
		 */
		PERMISSIONView("permission/view");

		/**
		 * 许可视图根目录
		 */
		public static final String ROOT = "/platform/authority/permission/";

		/**
		 * 路径
		 */
		private final String path;

		/**
		 * 构建
		 * 
		 */
		private Paths() {
			this.path = Paths.ROOT + this.name();
		}

		/**
		 * 构建
		 * 
		 * @param path
		 *            路径
		 */
		private Paths(final String path) {
			this.path = Paths.ROOT + path;
		}

		/**
		 * 获取
		 * 
		 * @return 路径
		 */
		public String path() {
			return this.path;
		}
	}

	/**
	 * 许可服务
	 */
	@Qualifier(AuthorityService.BEAN_ID)
	@Autowired(required = false)
	private AuthorityService authorityService;

	/**
	 * 许可验证
	 */
	@Qualifier(PermissionValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator permissionValidator;

	/**
	 * 许可、验证规则与处理模式验证
	 */
	@Qualifier(PeVaRuTransactModeValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator peVaRuTransactModeValidator;

	/**
	 * 许可：删除
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "permission/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> permissionDelete(final PermissionVo permissionVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getPermissionService().deletePermissionByIds(permissionVo.getPermission());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 许可：编辑
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @param model
	 *            上下文映射
	 * @return 许可编辑视图路径
	 */
	@RequestMapping(value = { "permission/edit.html" }, method = RequestMethod.GET)
	public String permissionEdit(final PermissionVo permissionVo, final Model model) {
		final PermissionDto permission = this.authorityService.getPermissionService().findPermissionById(permissionVo.getPermission());

		model.addAttribute(PermissionController.models.permission.name(), permission);

		return PermissionController.Paths.PERMISSIONEdit.path();
	}

	/**
	 * 许可：主界面
	 * 
	 * @return 许可主界面视图路径
	 */
	@RequestMapping(value = { "permission/index.html" })
	public String permissionIndex() {
		return PermissionController.Paths.PERMISSIONIndex.path();
	}

	/**
	 * 许可：主界面分页查询
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "permission/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> permissionIndexPagination(final PermissionVo permissionVo) {
		final PaginationDto<PermissionDto> permissionPagination = this.authorityService.getPermissionService()
		        .paginationPermissionByCode(permissionVo.getPermission());

		final Map<String, Object> permissionPaginationMap = Maps.newHashMap();

		permissionPaginationMap.put(Constants.total.stringValue(), permissionPagination.getTotalSize());
		permissionPaginationMap.put(Constants.rows.stringValue(), permissionPagination.getDataList());

		return permissionPaginationMap;
	}

	/**
	 * 许可：新增
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @param model
	 *            上下文映射
	 * @return 许可编辑视图路径
	 */
	@RequestMapping(value = { "permission/new.html" }, method = RequestMethod.GET)
	public String permissionNew(final PermissionVo permissionVo, final Model model) {
		model.addAttribute(PermissionController.models.permission.name(), permissionVo.getPermission());

		return PermissionController.Paths.PERMISSIONNew.path();
	}

	/**
	 * 许可：保存
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "permission/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String permissionSave(final PermissionVo permissionVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.permissionValidator.validate(permissionVo.getPermission(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.authorityService.getPermissionService().savePermissionByIdOrCode(permissionVo.getPermission());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 许可：更新
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "permission/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> permissionUpdate(final PermissionVo permissionVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getPermissionService().updatePermissionByIds(permissionVo.getPermission());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 许可：验证
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "permission/validationByCode.json" })
	@ResponseBody
	public Boolean permissionValidationByCode(final PermissionVo permissionVo) {
		try {
			final int count = this.authorityService.getPermissionService().readPermissionByCodeNqId(permissionVo.getPermission());

			return (count < 1);
		} catch (final Exception e) {
			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 许可：查看
	 * 
	 * @param permissionVo
	 *            许可视图对象
	 * @param model
	 *            上下文映射
	 * @return 许可查看编辑视图路径
	 */
	@RequestMapping(value = { "permission/view.html" }, method = RequestMethod.GET)
	public String permissionView(final PermissionVo permissionVo, final Model model) {
		final PermissionDto permission = this.authorityService.getPermissionService().findPermissionById(permissionVo.getPermission());

		model.addAttribute(PermissionController.models.permission.name(), permission);

		return PermissionController.Paths.PERMISSIONView.path();
	}

	/**
	 * 许可、验证规则与处理模式：删除
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "peVaRuTransactMode/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> peVaRuTransactModeDelete(final PermissionVo permissionVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getPermissionService().deletePeVaRuTransactModeByIds(permissionVo.getPeVaRuTransactMode());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 许可、验证规则与处理模式：编辑
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @param model
	 *            上下文映射
	 * @return 许可、验证规则与处理模式编辑视图路径
	 */
	@RequestMapping(value = { "peVaRuTransactMode/edit.html" }, method = RequestMethod.GET)
	public String peVaRuTransactModeEdit(final PermissionVo permissionVo, final Model model) {
		final PeVaRuTransactModeDto peVaRuTransactMode = this.authorityService.getPermissionService().findPeVaRuTransactModeById(
		        permissionVo.getPeVaRuTransactMode());

		model.addAttribute(PermissionController.models.peVaRuTransactMode.name(), peVaRuTransactMode);

		return PermissionController.Paths.PE_VA_RU_TRANSACT_MODEEdit.path();
	}

	/**
	 * 许可、验证规则与处理模式：主界面
	 * 
	 * @return 许可、验证规则与处理模式主界面视图路径
	 */
	@RequestMapping(value = { "peVaRuTransactMode/index.html" })
	public String peVaRuTransactModeIndex() {
		return PermissionController.Paths.PE_VA_RU_TRANSACT_MODEIndex.path();
	}

	/**
	 * 许可、验证规则与处理模式：主界面分页查询
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "peVaRuTransactMode/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> peVaRuTransactModeIndexPagination(final PermissionVo permissionVo) {
		final PaginationDto<PeVaRuTransactModeDto> peVaRuTransactModePagination = this.authorityService.getPermissionService()
		        .paginationPeVaRuTransactModeByCode(permissionVo.getPeVaRuTransactMode());

		final Map<String, Object> peVaRuTransactModePaginationMap = Maps.newHashMap();

		peVaRuTransactModePaginationMap.put(Constants.total.stringValue(), peVaRuTransactModePagination.getTotalSize());
		peVaRuTransactModePaginationMap.put(Constants.rows.stringValue(), peVaRuTransactModePagination.getDataList());

		return peVaRuTransactModePaginationMap;
	}

	/**
	 * 许可、验证规则与处理模式：新增
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @param model
	 *            上下文映射
	 * @return 许可、验证规则与处理模式编辑视图路径
	 */
	@RequestMapping(value = { "peVaRuTransactMode/new.html" }, method = RequestMethod.GET)
	public String peVaRuTransactModeNew(final PermissionVo permissionVo, final Model model) {
		model.addAttribute(PermissionController.models.peVaRuTransactMode.name(), permissionVo.getPeVaRuTransactMode());

		return PermissionController.Paths.PE_VA_RU_TRANSACT_MODENew.path();
	}

	/**
	 * 许可、验证规则与处理模式：保存
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "peVaRuTransactMode/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String peVaRuTransactModeSave(final PermissionVo permissionVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.peVaRuTransactModeValidator.validate(permissionVo.getPeVaRuTransactMode(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.authorityService.getPermissionService().savePeVaRuTransactModeByIdOrCode(permissionVo.getPeVaRuTransactMode());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 许可、验证规则与处理模式：更新
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "peVaRuTransactMode/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> peVaRuTransactModeUpdate(final PermissionVo permissionVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.authorityService.getPermissionService().updatePeVaRuTransactModeByIds(permissionVo.getPeVaRuTransactMode());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 许可、验证规则与处理模式：验证
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "peVaRuTransactMode/validationByCode.json" })
	@ResponseBody
	public Boolean peVaRuTransactModeValidationByCode(final PermissionVo permissionVo) {
		try {
			final int count = this.authorityService.getPermissionService().readPeVaRuTransactModeByCodeNqId(
			        permissionVo.getPeVaRuTransactMode());

			return (count < 1);
		} catch (final Exception e) {
			if (PermissionController.log.isDebugEnabled()) {
				PermissionController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 许可、验证规则与处理模式：查看
	 * 
	 * @param permissionVo
	 *            许可、验证规则与处理模式视图对象
	 * @param model
	 *            上下文映射
	 * @return 许可、验证规则与处理模式查看编辑视图路径
	 */
	@RequestMapping(value = { "peVaRuTransactMode/view.html" }, method = RequestMethod.GET)
	public String peVaRuTransactModeView(final PermissionVo permissionVo, final Model model) {
		final PeVaRuTransactModeDto peVaRuTransactMode = this.authorityService.getPermissionService().findPeVaRuTransactModeById(
		        permissionVo.getPeVaRuTransactMode());

		model.addAttribute(PermissionController.models.peVaRuTransactMode.name(), peVaRuTransactMode);

		return PermissionController.Paths.PE_VA_RU_TRANSACT_MODEView.path();
	}
}
